import React, { Component } from 'react'
// 类组件,必有一个render方法
// 类组件有状态state、更新状态：setState
// 事件绑定
// 生命周期函数：react定义好的函数，在组件的某个阶段自动执行的函数

class Timer extends Component {
    state = { time: new Date().toLocaleTimeString() }
    componentDidMount(){
        this.timerId = setInterval(()=>{
            console.log('timer');
            this.setState({
                time: new Date().toLocaleTimeString()
            })
        },1000)
    }
    componentWillUnmount(){
        clearInterval(this.timerId)
        console.log('WillUnmount')
    }
    render(){
        return (
            <div>
                {this.state.time}
            </div>
        )
    }
}

class Count extends Component {
    constructor(){
        super();
        this.state = {
            count: 0,
            topics: [1,2,3],
            isShowTimer: true
        }
        console.log('constructor');
    }
    handleClick = ()=>{
        this.setState({count: this.state.count+1})
    }
    addTopic = () => {
        this.setState({
            topics: [
                ...this.state.topics,
                Math.random()
            ]
        })
    }
    deleteTopic = (topic) => {
        this.setState({
            topics: this.state.topics.filter(item=>item!=topic)
        })
    }
    toggleTimer = () => {
        this.setState({
            isShowTimer: !this.state.isShowTimer
        })
    }
    componentDidMount(){
        // 只执行一次
        // 可以发请求
        console.log('componentDidMount')
    }
    componentDidUpdate(){
        // 每次状态更新都会执行
        console.log('DidUpdate');
    }
    render() {
        console.log('render');
        return (
            <div>
                {
                    this.state.isShowTimer && <Timer />
                }
                <button onClick={this.toggleTimer}>显示/隐藏Timer</button>
                <ul>
                    {
                        this.state.topics.map(item=>{
                            return (
                                <li key={item}>
                                    {item}
                                    <button onClick={()=>this.deleteTopic(item)}>删除</button>
                                </li>
                            )
                        })
                    }
                </ul>
                <button onClick={this.addTopic}>添加topics</button>
                <h1>{this.state.count}</h1>
                <button onClick={this.handleClick}>点击+1</button>
            </div>
        )
    }
}

export default Count;

// class Person {
//     name = 'abc'
//     say() {
//         console.log(this.name)
//     }
// }
// const p1 = new Person()
// console.log(p1.name);
// p1.say();